<?php
#
# UNLVSpatial: a dmBridge module for spatial content
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class UNLVSpatialQuery extends DMAbstractQuery implements DMQuery {

	/** @var array Array of UNLVSpatialQueryTerm objects */
	private $terms = array();


	/**
	 * @return DMInternalURI URI of the query
	 */
	public function getFeedURI() {
		return $this->getURI("atom");
	}

	/**
	 * @return Array of DMObjects
	 * @throws DMInternalErrorException
	 */
	public function getSearchResults() {
		if (count($this->results)) {
			return $this->results;
		}

		$ds = DMDataStoreFactory::getDataStore();
		switch ($ds->getType()) {
			case DMDataStoreType::PDO_MySQL:
				$ds = UNLVSpatialMySQLDataStore::getInstance();
				break;
			case DMDataStoreType::PDO_SQLite:
				$ds = UNLVSpatialSQLiteDataStore::getInstance();
				break;
		}

		$this->num_results = $ds->getNumObjectsMatchingQuery($this);
		return $ds->getObjectsMatchingQuery($this);
	}

	/**
	 * @param UNLVSpatialQueryTerm term
	 */
	public function addQueryTerm(UNLVSpatialQueryTerm $term) {
		$this->terms[] = $term;
	}

	/**
	 * @return Array of UNLVSpatialQueryTerm objects
	 */
	public function getQueryTerms() {
		return $this->terms;
	}

	/**
	 * @return DMInternalURI URI of the query
	 */
	public function getURI($representation = "html") {
		$terms = $this->getQueryTerms();
		$collections = $this->getCollections();
		$qs = array();

		for ($i = 1; $i <= count($terms); $i++) {
			$qs['mode' . $i] = $terms[$i-1]->getMatchingMode();
			$sp_obj = $terms[$i-1]->getExampleObject();
			$qs['nlat' . $i] = $sp_obj->getSpatialNorthLat();
			$qs['slat' . $i] = $sp_obj->getSpatialSouthLat();
			$qs['elong' . $i] = $sp_obj->getSpatialEastLong();
			$qs['wlong' . $i] = $sp_obj->getSpatialWestLong();
		}

		$qs['aliases'] = array();
		for ($i = 1; $i <= count($collections); $i++) {
			$qs['aliases'][] = $collections[$i-1]->getAlias();
		}

		return DMInternalURI::getURIWithParams("api/1/spatial_search", $qs,
				$representation);
	}

}
